package user

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/ecomp-analyzer-services/consts"
	"gitee.com/bobo-rs/ecomp-analyzer-services/enums"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/model"
	"gitee.com/bobo-rs/ecomp-analyzer-services/framework/service"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/exception"
	"gitee.com/bobo-rs/ecomp-analyzer-services/library/tools"
	"github.com/gogf/gf/v2/errors/gerror"
)

// AuthLoginAdminUser 登录用户认证管理员信息
func (u *sUser) AuthLoginAdminUser(ctx context.Context) error {
	user := service.BizCtx().GetUser(ctx)
	if user == nil {
		return gerror.New(`请登录`)
	}
	var (
		detail    *model.UserAdminDetailItem
		cacheKey  = tools.CacheKey(consts.LoginAdminAuthToken, user.AccountToken)
		cacheFunc = func(ctx context.Context) (interface{}, error) {
			return u.ProcessAdminDetailByUid(ctx, user.Uid)
		}
	)

	// 缓存管理员信息
	r, err := sredis.NewCache().GetOrSetFunc(ctx, cacheKey, cacheFunc, consts.LoginAuthExpire)
	if err != nil {
		return err
	}

	// 格式化
	if err = r.Struct(&detail); err != nil {
		return exception.NewCodef(enums.ErrorNotAdmin, `未授权管理%s`, err.Error())
	}

	// 管理员状态
	if enums.UserAdminStatus(detail.ManageStatus) != enums.UserAdminStatusOk {
		return exception.Newf(`账户已%s`, enums.UserAdminStatus(detail.ManageStatus).Fmt())
	}

	// 缓存管理员信息
	user.IsAdmin = true
	user.IsSupper = detail.IsSuperManage == 1
	service.BizCtx().SetUser(ctx, user)
	service.BizCtx().SetDataValue(ctx, enums.ContextDataAdminUser, detail)
	return nil
}

// GetAdminUser 获取管理员登录详情
func (u *sUser) GetAdminUser(ctx context.Context) *model.UserAdminDetailItem {
	// 获取管理员用户信息
	value := service.BizCtx().GetValue(ctx, enums.ContextDataAdminUser)
	if value == nil {
		return nil
	}
	// 断言管理员详情
	if detail, ok := value.(*model.UserAdminDetailItem); ok {
		return detail
	}
	return nil
}
